/**
 *
 */
package utils;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import mainApp.HighScore;

public class DataAdapter {

    Scanner inputScan = new Scanner(System.in);
    StringTokenizer st;
    Utils utility = new Utils();

    public DataAdapter() {
    }

    public void addNewWordFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showOpenDialog(fileChooser);
        File selectedFile = fileChooser.getSelectedFile();
        String temp = selectedFile.getAbsoluteFile().getName().substring(0, (int) selectedFile.getAbsoluteFile().getName().length() - 6);
        createNewWordFile(temp);
        File wf = new File(checkSettings().getProperty("wordListsLocation") + (selectedFile.getAbsoluteFile().getName()));
        try {
            InputStream fileIn = new FileInputStream(selectedFile);
            OutputStream fileOut = new FileOutputStream(wf);
            byte[] dataBuffer = new byte[1024];
            int len;
            try {
                while ((len = fileIn.read(dataBuffer)) > 0) {
                    fileOut.write(dataBuffer, 0, len);
                }
                fileIn.close();
                fileOut.close();
            } catch (IOException ex) {
                Logger.getLogger(DataAdapter.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataAdapter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public int getNoOfFilesInDir(String dir) {
        File file = new File(dir);
        int count = 0;
        for (File fileTrack : file.listFiles()) {
            if (fileTrack.getAbsolutePath().toLowerCase().endsWith(".wlist")) {
                count++;
            }
        }
        return count;
    }

    public Object[] getFileNameFromDir(String dir) {
        File file = new File(dir);
        int count = 0;
        Object[] fileNames = new Object[getNoOfFilesInDir(checkSettings().getProperty("wordListsLocation")) + 1];
        for (File fileTrack : file.listFiles()) {
            if (fileTrack.getAbsolutePath().toLowerCase().endsWith(".wlist")) {
                count++;
                fileNames[count] = fileTrack.getAbsolutePath();
            }
        }
        fileNames[0] = "Default";
        return fileNames;
    }

    public Properties checkSettings() {
        Properties p = new Properties();
        try {
            p.load(new FileInputStream("settings.ini"));
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "No settings file found. One will be created.");
            File wf = new File("settings.ini");
            try {
                wf.createNewFile();
            } catch (IOException e1) {
            }
            p.setProperty("wordListsLocation",  this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "../../");
            Writer out;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("settings.ini", true)));
                p.store(out, null);
            } catch (IOException e2) {
            }
        }
        return p;
    }

    public void setWordListsLocation() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setAcceptAllFileFilterUsed(false);
        if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            Properties p = checkSettings();
            p.setProperty("wordListsLocation", fileChooser.getCurrentDirectory().getAbsolutePath() + "\\" + fileChooser.getSelectedFile().getName());
            Writer out;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("settings.ini", true)));
                p.store(out, null);
            } catch (IOException e) {
            }
        }
    }

    public boolean createNewDir(String dir) {
        boolean created = (new File(dir)).mkdirs();
        return created;
    }

    public boolean createNewWordFile(String file) {
        boolean created = false;
        File wf = new File(checkSettings().getProperty("wordListsLocation") + file + ".wlist");
        if (!wf.exists()) {
            try {
                created = wf.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(DataAdapter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return created;
    }

    public void addWordToFile(String file, String word) {
        if (!(new File((checkSettings().getProperty("wordListsLocation")) + file + ".wlist")).exists()) {
            try {
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(checkSettings().getProperty("wordListsLocation") + file + ".wlist", true)));
                out.write(word);
            } catch (IOException ex) {
            }
        }
    }

    public ArrayList<String> getWordList(InputStream selection) {
        ArrayList<String> wordList = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(selection));
            String currentWord;
            Pattern p = Pattern.compile("[a-zA-Z]*");
            while ((currentWord = br.readLine()) != null) {
                if (p.matcher(currentWord).matches() == true) {
                    wordList.add(currentWord);
                } else {
                    System.out.println("Non conforming word found.");
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("File cant be read.");
        }
        return wordList;
    }

    public ArrayList<String> getWordList(String selection) {
        ArrayList<String> wordList = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(selection)));
            String currentWord;
            Pattern p = Pattern.compile("[a-zA-Z]*");
            while ((currentWord = br.readLine()) != null) {
                if (p.matcher(currentWord).matches() == true) {
                    wordList.add(currentWord);
                } else {
                    System.out.println("Non conforming word found.");
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("File cant be read.");
        }
        return wordList;
    }

    public ArrayList<HighScore> getHighScores() {
        ArrayList<HighScore> highScores = new ArrayList<HighScore>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("HighScores.txt")));
            String currentScore;
            String currentUser;
            for (int i = 0; i < 10; i++) {
                currentUser = br.readLine();
                currentScore = br.readLine();
                highScores.add(new HighScore(currentUser, Integer.parseInt(currentScore)));
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("File cant be read.");
        }
        return highScores;
    }

    public int addHighScore(String user, int score) {

        ArrayList<HighScore> highScores = getHighScores();
        int highscorePos = 0;

        utility.checkForHighScoreFile();

        for (int i = 0; i < 10; i++) {
            if (score > highScores.get(i).getScore()) {
                highScores.add(i, new HighScore(user, score));
                highScores = utility.truncateHighScoreArrayList(highScores);
                highscorePos = i + 1;
                break;
            }
        }
        try {
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("HighScores.txt", false)));
            out.write("");
            out.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("File cant be read.");
        }
        for (int i = 0; i < 10; i++) {
            try {
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("HighScores.txt", true)));
                out.write(highScores.get(i).getUser());
                out.write(System.getProperty("line.separator"));
                out.write(String.valueOf(highScores.get(i).getScore()));
                out.write(System.getProperty("line.separator"));
                out.close();
            } catch (FileNotFoundException e) {
                System.out.println("File not found.");
            } catch (IOException e) {
                System.out.println("File cant be read.");
            }
        }
        return highscorePos;
    }
}
